import { request } from './request'

export interface ProjectTypeItem {
  id: number
  name: string
  description?: string
  code?: string
  dialogPath?: string
  [key: string]: any
}

interface ProjectTypeListPayload {
  list?: ProjectTypeItem[]
  records?: ProjectTypeItem[]
  data?: ProjectTypeItem[]
}

const normalizeProjectTypes = (
  payload: ProjectTypeListPayload | ProjectTypeItem[] | undefined | null
) => {
  if (Array.isArray(payload)) {
    return payload
  }
  if (!payload) {
    return []
  }
  if (Array.isArray(payload.list)) {
    return payload.list
  }
  if (Array.isArray(payload.records)) {
    return payload.records
  }
  if (Array.isArray(payload.data)) {
    return payload.data
  }
  return []
}

export async function fetchProjectTypeList(
  params: Record<string, any> = {}
): Promise<ProjectTypeItem[]> {
  const data = await request<ProjectTypeListPayload | ProjectTypeItem[]>({
    url: '/lowcode3/api/project/type/list',
    data: params
  })
  return normalizeProjectTypes(data)
}
